var { login } = require("../model/userModel")
var jwt = require('jsonwebtoken')

const loginCtr = async (req, res) => {
    const query = {
        username: req.body.username,
        password: req.body.password
    }
    let result = await login(query)

    if (result.length !== 0) {
        //生成token
        console.log(result)
        let payload = {
            username: req.body.username
        }
        let secrect = 'MY_NAME_IS_HMM'
        let token = jwt.sign(payload, secrect, //生成token
            {
                expiresIn: 60 * 5 //指定token生效的事件
            }
        )

        res.send({ status: 200, msg: "登入成功", token: token, usname: req.body.username, nickName: result[0].nickName })
    } else {
        res.send({ status: 301, msg: "账号或者密码错误" })
    }
}


const checkCtr = (req, res, next) => {
    //验证使用 jwt.verify(token,secrect,callback)
    let token = req.body.token
    let secrect = 'MY_NAME_IS_HMM'
    jwt.verify(token, secrect, (err, decode) => {
        //如果验证不通过  err就有值了
        if (err) {
            res.send({ msg: '验证失败' })
        } else {
            console.log(decode)
            res.send({ msg: '验证通过', username: decode.username });
        }
    })
}

module.exports = {
    loginCtr,
    checkCtr
}